<template>
    <!-- <img :src alt="" style="height:1rem"> -->
    <div
        style="text-align: center;width: 100%;height: 100vh;padding:.5rem;display: flex;flex-direction: column;align-items: center;justify-content: center;">

        <span style="color: #000;font-size: 1rem;">
            放入标本后，请点击关闭按钮，确认关闭
        </span>
        <a-button type="primary" @click="close()" block>关闭</a-button>
    </div>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router'
import { isAndroid, getTime, base64ToFile } from '@/utils/UtilFun'
import { onMounted, onUnmounted, ref, watch, watchEffect } from 'vue'
import { db } from "@/utils/DexieDB"
import { addAlarmApi, uploadPutsFileApi } from '@/API/API'

const router = useRouter()
const putData = JSON.parse(router.currentRoute.value.query.data as string)

const src = ref('')
const count = ref(0)
const device = ref<device>()

let timer: any = null, speakTimer: any = null, isSendData = false

timer = setInterval(() => {
    if (isAndroid()) {
        console.log('读取轨道锁状态');
        count.value++
        // window.ClosetAndroid.readTrackLock()
        if (count.value > 10 && !isSendData) {
            handleAlarmLogic()
        }
        if (count.value > 30) {
            handleTimeoutLogic()
        }
    }
}, 1000)

function handleAlarmLogic() {
    addAlarm('舱门未关闭报警')
    console.log('发送tts');
    window.ClosetAndroid.ttsSpeak('您好，操作完成后，请及时关闭舱门，舱门未关闭，请勿放入试管！', 20);

}

function handleTimeoutLogic() {
    cleanupTimers();
    window.ClosetAndroid.ttsStop();
    // window.ClosetAndroid.closeTrackLock();
    window.ClosetAndroid.closeTrack()
    router.push('/Home');
}


function cleanupTimers() {
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
    if (speakTimer) {
        clearInterval(speakTimer);
        speakTimer = null;
    }
}
// 舱门未关闭报警记录
async function addAlarm(msg: string, flag = false) {

    if (!flag && isSendData) return

    isSendData = true
    const time = getTime()
    db.error.add({
        time,
        info: msg,
    }).then(async () => {
        return await db.device.get(1)
    }).then(device => {
        return device?.serial
    }).then(serial => {
        addAlarmApi({
            alarmType: msg,
            alarmData: time,
            serial
        }).then(res => {
            if (res.code === 200) {
                console.log('报警记录发送成功！');
            } else {
                console.log('报警记录发送失败！');
            }
        }).catch(({ error, url, fetchOptions }) => {
            db.retryTasks.add({
                id: Date.now(),
                time: getTime(),
                url,
                info: fetchOptions
            }).then((id) => {
                console.log('重试任务添加报警记录成功', id);
            }).catch(err => {
                console.log('重试任务添加报警记录失败', err);
            })
        })
    })
}

// 关门
function close() {
    if (timer) {
        clearInterval(timer)
    }
    if (speakTimer) {
        clearInterval(speakTimer)
    }
    if (isAndroid()) {
        console.log('关闭轨道锁');
        window.ClosetAndroid.ttsStop();
        // window.ClosetAndroid.closeTrackLock();
        window.ClosetAndroid.closeTrack()

        router.push('/Home')
    }
}

// 提取照片处理逻辑为独立函数
function processPhoto(path: string): File {
    console.log('处理照片路径:', path);
    const base64 = window.ClosetAndroid.readFileAsBase64(path)
    // 提取文件名
    const fileName = path.substring(path.lastIndexOf('/') + 1);
    const file = base64ToFile(base64, fileName);
    return file;
}

// 提取数据库存储逻辑为独立函数
async function savePhotoToDatabase(file: File, routeName: string): Promise<void> {
    try {
        Promise.all(putData.map(async (item: number) => {
            console.log('更新数据:id:', item);
            const record = await db.testTube.get(item) as testTube;

            if (record) {
                if (routeName === 'OpenDoor') {
                    record.putImg = file;
                } else if (routeName === 'Setting') {
                    record.outImg = file;
                    record.outTime = new Date().toLocaleString('sc-se');
                }
                // 更新记录
                await db.testTube.update(item, record);
                await db.testTubeHistory.update(item, record);
            }
        })).then(async () => {
            console.log('照片数据保存成功');
            await sendData(file)
        })
    } catch (err) {
        console.log('照片数据保存失败:', err);
    }
}

async function sendData(file: File) {
    const deviceInfo = await db.device.get(1)
    const used = await db.testTube.count()
    const putRecords = await db.testTube.bulkGet(putData)
    uploadPutsFileApi({
        closetPuts: JSON.stringify({
            serial: deviceInfo?.serial,
            tubeUse: used,
            tubeRemain: deviceInfo!.allNum - used,
            data: putRecords
        }),
        file
    }).then(res => {
        console.log(res);
        console.log('put 发送完毕');

        if (device.value!.allNum - used <= device.value!.maxVacantNum) {
            addAlarm('舱位剩余空位不足', true)
        }
    }).catch(({ error, url, fetchOptions }) => {
        console.log('put发送失败');
        console.log(error, url, fetchOptions);

        const file = fetchOptions.body.get('file') as File
        const closetPutsData = fetchOptions.body.get('closetPuts') as string
        // 处理 FormData 序列化问题
        db.retryTasks.add({
            id: Date.now(),
            time: getTime(),
            url,
            info: { closetPuts: closetPutsData },
            file
        }).then((id) => {
            console.log('重试任务添加放样成功', id);
        }).catch(err => {
            console.log('重试任务添加放样失败', err);
        })
    })
}


onMounted(async () => {
    window.onPhotoCapturedPut = (path: string) => {
        console.log('onPhotoCapturedPut', path);
        try {
            // 处理照片
            const file = processPhoto(path);
            // 显示预览
            src.value = URL.createObjectURL(file);
            // 保存到数据库
            savePhotoToDatabase(file, router.currentRoute.value.name as string);
        } catch (error) {
            console.error('照片处理失败:', error);
        }
    }
    device.value = await db.device.get(1)
    // 关闭轨道
    window.closeTrackLock = () => {
        close()
    }
})

onUnmounted(() => {
    cleanupTimers();
});





</script>
<style lang="scss" scoped>
.ant-btn {
    font-size: .75rem;
    padding: 0.25rem;
    height: auto;
}
</style>